package com.example.demo.service.impl;

import com.example.demo.controller.TestController;
import com.example.demo.service.LogWriterService;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class LogWriterServiceImpl implements LogWriterService {

    private static final String ROOT_PATH = new ApplicationHome().getDir().getPath();
    private static final String LOG_PATH = ROOT_PATH + File.separator + "chat.log";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    private final AtomicInteger messageCount = new AtomicInteger(0);


    private static final String[] LOG_LEVELS = {"INFO", "WARN", "ERROR", "DEBUG"};
    private static final String[] MESSAGES = {
            "系统正常运行中...",
            "检测到新用户登录",
            "数据库连接池状态更新",
            "缓存清理完成",
            "正在进行数据同步",
            "系统资源使用率: {}%",
            "网络延迟: {}ms",
            "内存使用率: {}%",
            "CPU使用率: {}%"
    };

    @Override
    @Scheduled(fixedRate = 100)
    public void writeLog() {
        if (TestController.flag) {
            try {
                Path path = Paths.get(LOG_PATH);
                if (!Files.exists(path)) {
                    Files.createFile(path);
                }
            } catch (IOException e) {
                throw new RuntimeException("Failed to initialize log file: " + LOG_PATH, e);
            }
            // 获取随机的文本内容，并写入文件
            String logEntry = generateLogEntry();
            try (FileChannel channel = FileChannel.open(Paths.get(LOG_PATH),
                    StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
                FileLock lock = channel.lock();
                try {
                    channel.write(StandardCharsets.UTF_8.encode(logEntry));
                } finally {
                    lock.release();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String generateLogEntry() {
        Random random = new Random();
        String level = LOG_LEVELS[random.nextInt(LOG_LEVELS.length)];
        String message = MESSAGES[random.nextInt(MESSAGES.length)];
        if (message.contains("{}")) {
            message = message.replace("{}", String.valueOf(random.nextInt(100)));
        }
        return String.format("[%s] [%s] [消息序号:%d] %s\n",
                DATE_FORMAT.format(new Date()),
                level,
                messageCount.incrementAndGet(),
                message
        );
    }

}